package com.sservice.web.controller.pc;

import com.google.common.io.Files;
import com.sservice.base.entity.dto.BaseResult;
import com.sservice.base.utils.ImgUtils;
import com.sservice.common.Constants;
import com.sservice.commonBusiness.service.FileService;
import com.sservice.web.utils.FileList;
import com.sservice.web.utils.ImageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * ref:http://www.iteye.com/topic/264457
 */
@Controller
public class CutImageController {

    @Autowired
    FileService fileService;

    @RequestMapping(value = "/cutimage", method = RequestMethod.POST)
    public
    @ResponseBody
    BaseResult cutImage(@RequestParam("image") MultipartFile file, HttpServletRequest request) throws IOException {
        if (file.isEmpty()) {
            return new BaseResult(false, "file is empty", 400);
        }
        int x = Integer.valueOf(request.getParameter("x"));
        int y = Integer.valueOf(request.getParameter("y"));
        int width = Integer.valueOf(request.getParameter("width"));
        int height = Integer.valueOf(request.getParameter("height"));
        if (width == 0 || height == 0) {
            return new BaseResult(false, "parameters error", 400);
        }
        //nginx访问路径
        String webPath = Constants.nginxVisitUrl;
        //图片保存路径
        String imgPath = Constants.thumbnailPath;
        String fileName = UUID.randomUUID().toString().replaceAll("-", "");
        String extension = Files.getFileExtension(file.getOriginalFilename());

        File imgBig = new File(imgPath + fileName + "_big." + extension);
        file.transferTo(imgBig);

        File imgSmall = new File(imgPath + fileName + "_small." + extension);
        imgSmall.createNewFile();

        ImageUtil.cutImage(imgBig, new FileOutputStream(imgSmall), x, y, width, height);

        return new BaseResult(true, webPath + fileName + "_small." + extension, 200);
    }

    @RequestMapping(value = "/path-cut-image", method = RequestMethod.POST)
    @ResponseBody
    public BaseResult pathCutImage(HttpServletRequest request) throws IOException {

        int x = Integer.valueOf(request.getParameter("x"));
        int y = Integer.valueOf(request.getParameter("y"));
        int width = Integer.valueOf(request.getParameter("w"));
        int height = Integer.valueOf(request.getParameter("h"));
        String path = String.valueOf(request.getParameter("path"));
        if (width == 0 || height == 0 || path == null) {
            return new BaseResult(false, "parameters error", 400);
        }
        String webPath = Constants.nginxVisitUrl;
        String imgPath = Constants.thumbnailPath;
        path = path.replace(webPath, imgPath);

        File imgBig = new File(path);
        String small = path.replace("_f.", "_c.");
        System.out.println(small);
        File imgSmall = new File(small);
        imgSmall.createNewFile();

        ImageUtil.cutImage(imgBig, new FileOutputStream(imgSmall), x, y, width, height);
        Map map = new HashMap();
        small = small.replace(imgPath, webPath);
        map.put("path", small);
        return new BaseResult(true, map);
    }

    @ResponseBody
    @RequestMapping(value = "/pages/error/maxUploadExceeded", method = RequestMethod.GET)
    public BaseResult handleMaxUploadSizeExceededException(Exception ex, HttpServletRequest request) {
        if (ex instanceof org.springframework.web.multipart.MaxUploadSizeExceededException) {
            return new BaseResult(false, "最大上传文件不能超过5M!", 403);
        }
        return new BaseResult(false, "服务端错误!", 500);
    }

    /***
     * @param file
     * @param type 文件类型：默认图片，papaer合同
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public BaseResult upload(@RequestParam("file") MultipartFile file,
                             Integer from,
                             Integer folderId,
                             String type, HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (file.isEmpty()) {
            return new BaseResult(false, "file is empty", 400);
        }
        response.setHeader("Content-type", "text/html");
        //图片保存路径
        String imgPath = "";
        String webPath = Constants.nginxVisitUrl;
        if ("paper".equals(type)) {
            imgPath = Constants.orderpaperPath;
        } else {
            imgPath = Constants.thumbnailPath;
        }

        String extension = Files.getFileExtension(file.getOriginalFilename()); // 后缀
        String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "_f." + extension; // 新文件名
        String monthPath = getDayPath(); //
        String diskPath = imgPath + monthPath;
        File path = new File(diskPath);
        webPath += monthPath;
        if (!path.exists()) {
            path.mkdir(); // emptmp
        }
        File imgBig = new File(diskPath + fileName);
        String url = webPath + fileName;
        file.transferTo(imgBig);
        com.sservice.commonBusiness.e.File file1 = fileService.saveFileInfo(file.getOriginalFilename(),
                null, null, from != null ? from : Integer.valueOf(2), //默认后台
                ImgUtils.isImage(imgBig) ? 0 : 1, url, extension,
                diskPath + fileName, file.getSize(), folderId == null ? 0 : folderId);

        Map map = new HashMap();
        map.put("path", url);
        map.put("currentFileName", file.getOriginalFilename());
        map.put("fileId", file1.getId());
        map.put("currentFileSize", fileName + "." + extension);
        map.put("currentWidth", fileName + "." + extension);
        map.put("status", true);

        return new BaseResult(true, map);
    }

    /**
     * 批量上传
     *
     * @param file
     * @param from
     * @param folderId
     * @param type
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/uploadFiles", method = RequestMethod.POST)
    public BaseResult uploadFiles( @ModelAttribute FileList file,
                                  Integer from,
                                  Integer folderId,
                                  String type, HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (file.getFile().size() == 0) {
            return new BaseResult(false, "请选择文件上传", 400);
        }
        response.setHeader("Content-type", "text/html");
        List list = new ArrayList<>();
        for (MultipartFile file1 : file.getFile()) {
            BaseResult item = upload(file1, from, folderId, type, request, response);
            list.add(item.getData());
        }
        return new BaseResult(true, list);
    }

    public String getDayPath() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String datePath = sdf.format(date) + "/";
        return datePath;
    }


}
